package com.notice.view;

import com.notice.model.CommentModel;
import com.notice.viewmodel.CommentViewModel;
import com.notice.util.ResponseUtil;
import com.notice.common.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

@Controller
@RequestMapping("/Comment")
@CrossOrigin
public class CommentView implements Observer {

    @Autowired
    private CommentViewModel commentViewModel;
    
    @PostConstruct
    public void init() {
        commentViewModel.addObserver(this);
    }

    @PostMapping("/Add")
    @ResponseBody
    public ResponseEntity<?> addComment(@RequestBody CommentModel comment) {
        if(commentViewModel.addComment(comment)) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(Constants.ErrorCodes.LOGIN_FAIL, Constants.Messages.OPERATION_FAIL);
    }
    
    @PostMapping("/Find")
    @ResponseBody
    public ResponseEntity<?> findComments(@RequestBody CommentModel query) {
        return ResponseUtil.success(commentViewModel.findComments(query));
    }
    
    @PostMapping("/Delete")
    @ResponseBody
    public ResponseEntity<?> deleteComment(@RequestBody CommentModel comment) {
        if(commentViewModel.deleteComment(comment)) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(Constants.ErrorCodes.DELETE_FAIL, Constants.Messages.OPERATION_FAIL);
    }
    
    @PostMapping("/Update")
    @ResponseBody
    public ResponseEntity<?> updateComment(@RequestBody CommentModel comment) {
        if(commentViewModel.updateComment(comment)) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(Constants.ErrorCodes.UPDATE_FAIL, Constants.Messages.UPDATE_FAIL);
    }
    
    @Override
    public void update(Observable o, Object arg) {
        // 处理 ViewModel 的状态更新
        // 可以在这里处理评论状态的变化，比如实时更新等
        System.out.println("Comment state updated: " + arg);
    }

    @PostMapping("/GetSumVote")
    @ResponseBody
    public ResponseEntity<?> GetSumVote(@RequestBody CommentModel query) {
        HashMap map = new HashMap();
        map.put("votesum",commentViewModel.findComments(query));
        return ResponseUtil.success(map);
    }
} 